package avicit.bdp.dds.server.worker.task.shell;

import avicit.bdp.common.utils.DateUtils;
import avicit.bdp.dds.dispatch.process.Property;
import avicit.bdp.dds.dispatch.process.ResourceInfo;
import avicit.bdp.dds.dispatch.task.AbstractParameters;
import avicit.bdp.dds.dispatch.task.shell.ShellParameters;
import avicit.bdp.core.util.json.JSONUtils;
import avicit.bdp.dds.common.Constants;
import avicit.bdp.dds.common.utils.OSUtils;
import avicit.bdp.dds.common.utils.ParameterUtils;
import avicit.bdp.dds.server.entity.TaskExecutionContext;
import avicit.bdp.dds.server.utils.ParamUtils;
import avicit.bdp.dds.server.worker.task.AbstractTask;
import avicit.bdp.dds.server.worker.task.CommandExecuteResult;
import avicit.bdp.dds.server.worker.task.ShellCommandExecutor;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.nio.file.attribute.FileAttribute;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.Map;
import java.util.Set;

/**
 * shell task
 */
public class ShellTask extends AbstractTask {

  /**
   * shell parameters
   */
  private ShellParameters shellParameters;

  /**
   * shell command executor
   */
  private ShellCommandExecutor shellCommandExecutor;

  /**
   *  taskExecutionContext
   */
  private TaskExecutionContext taskExecutionContext;

  /**
   * constructor
   * @param taskExecutionContext taskExecutionContext
   * @param logger    logger
   */
  public ShellTask(TaskExecutionContext taskExecutionContext, Logger logger) {
    super(taskExecutionContext, logger);

    this.taskExecutionContext = taskExecutionContext;
    this.shellCommandExecutor = new ShellCommandExecutor(this::logHandle,
            taskExecutionContext,
            logger);
  }

  @Override
  public void init() {
    logger.info("shell task params {}", taskExecutionContext.getTaskParams());

    shellParameters = JSONUtils.parseObject(taskExecutionContext.getTaskParams(), ShellParameters.class);

    if (!shellParameters.checkParameters()) {
      throw new RuntimeException("shell task params is not valid");
    }
  }

  @Override
  public void handle() throws Exception {
    try {
      // construct process
      CommandExecuteResult commandExecuteResult = shellCommandExecutor.run(buildCommand());
      setExitStatusCode(commandExecuteResult.getExitStatusCode());
      setAppIds(commandExecuteResult.getAppIds());
      setProcessId(commandExecuteResult.getProcessId());
    } catch (Exception e) {
      logger.error("shell task error", e);
      setExitStatusCode(Constants.EXIT_CODE_FAILURE);
      throw e;
    }
  }

  @Override
  public void cancelApplication(boolean cancelApplication) throws Exception {
    // cancel process
    shellCommandExecutor.cancelApplication();
  }

  /**
   * create command
   * @return file name
   * @throws Exception exception
   */
  private String buildCommand() throws Exception {
    // generate scripts
    String fileName = String.format("%s/%s_node.%s",
            taskExecutionContext.getExecutePath(),
            taskExecutionContext.getTaskAppId(), OSUtils.isWindows() ? "bat" : "sh");

    Path path = new File(fileName).toPath();

    if (Files.exists(path)) {
      return fileName;
    }

    String script = shellParameters.getRawScript().replaceAll("\\r\\n", "\n");
    /**
     *  combining local and global parameters
     */
    Map<String, Property> paramsMap = ParamUtils.convert(ParamUtils.getUserDefParamsMap(taskExecutionContext.getDefinedParams()),
            taskExecutionContext.getDefinedParams(),
            shellParameters.getLocalParametersMap(),
            taskExecutionContext.getCmdTypeIfComplement(),
            taskExecutionContext.getScheduleTime());
    if (paramsMap != null){
      script = ParameterUtils.convertParameterPlaceholders(script, ParamUtils.convert(paramsMap));
    }
    // new
    // replace variable TIME with $[YYYYmmddd...] in shell file when history run job and batch complement job
    if (paramsMap != null) {
      if (taskExecutionContext.getScheduleTime() != null) {
        String dateTime = DateUtils.format(taskExecutionContext.getScheduleTime(), Constants.PARAMETER_FORMAT_TIME);
        Property p = new Property();
        p.setValue(dateTime);
        p.setProp(Constants.PARAMETER_SHECDULE_TIME);
        paramsMap.put(Constants.PARAMETER_SHECDULE_TIME, p);
      }
      script = ParameterUtils.convertParameterPlaceholders2(script, ParamUtils.convert(paramsMap));
    }

    // 数据质量任务特殊处理
    if (this.taskExecutionContext.getProjectId().equals("777777")) {
      // 生成Task Json配置文件
      ResourceInfo res = shellParameters.getResourceList().get(0);
      String jsonFilePath = writeJson2File("job.json", res.getRes());

      script = String.format(script, jsonFilePath, this.taskExecutionContext.getProcessInstanceId());

      logger.info("生成数据质量Script成功,脚本内容：" + script);
    }

    shellParameters.setRawScript(script);

    logger.info("raw script : {}", shellParameters.getRawScript());
    logger.info("task execute path : {}", taskExecutionContext.getExecutePath());

    Set<PosixFilePermission> perms = PosixFilePermissions.fromString(Constants.RWXR_XR_X);
    FileAttribute<Set<PosixFilePermission>> attr = PosixFilePermissions.asFileAttribute(perms);

    if (OSUtils.isWindows()) {
      Files.createFile(path);
    } else {
      Files.createFile(path, attr);
    }

    Files.write(path, shellParameters.getRawScript().getBytes(), StandardOpenOption.APPEND);

    return fileName;
  }

  @Override
  public AbstractParameters getParameters() {
    return shellParameters;
  }

  /**
   * 生成Task Json文件
   * @param fileName
   * @param json
   * @return
   */
  private String writeJson2File(String fileName, String json) {
    // generate json
    String filePath = String.format("%s/%s_%s", taskExecutionContext.getExecutePath(), taskExecutionContext.getTaskAppId(), fileName);
    Path path = new File(filePath).toPath();
    if (Files.exists(path)) {
      return fileName;
    }
    // create json file
    try {
      FileUtils.writeStringToFile(new File(filePath), json, StandardCharsets.UTF_8);
    } catch (IOException e) {
      e.printStackTrace();
    }

    logger.info("生成数据质量Task JSON文件成功,文件名：" + filePath);

    return filePath;
  }

}
